let express = require('express');
let path = require('path');
let app = express();
let config = require('./js/config.js');

// 解析application/json类型的数据
app.use(express.json());
// 解析application/x-www-form-urlencoded类型的数据
app.use(express.urlencoded({extended: true}));

// 挂载一个响应中间件
let {responseMiddleware} = require('./js/middleware/responseMiddleware.js');
app.use(responseMiddleware);

// 静态资源中间件
app.use(express.static(path.join(__dirname, 'public')));









const mysql = require('mysql2/promise');
const pool = mysql.createPool(config.mysqlConfig);
app.get('/transaction', async (request, response) => {
    const conn = await pool.getConnection();
    await conn.beginTransaction();
    console.log('Transaction started');
    try {
        await conn.query('INSERT INTO mo_goods SET name= ?', 'Alice' );
        await conn.query('INSERT INTO mo_goods SET name= ?', 'Bob' );
        await conn.query('INSERT INTO mo_goods SET name= ?', 'Charlie' );
        let sql = 'select id,name,price from mo_goods where id>75 order by id desc';
        let res = await conn.query(sql)
        console.log(res[0])
        await conn.commit();
        console.log('Transaction completed successfully');
        response.send('Transaction completed');
    } catch (err) {
        await conn.rollback();
        console.error('Transaction failed:', err);
        response.status(500).send('Transaction failed');
    } finally {
        conn.release();
    }
});

















// 路由设置
let routes = require('./routes/routes');
const {baseModelUseMysql2} = require("./js/service/baseModelUseMysql2");
app.use('/', routes);
app.all('*', (req, res, next) => {
    res.error(config.result.notFound)
});

app.listen(config.port, () => {
    console.log('express server running at http://127.0.0.1:' + config.port)
})